//
//  HJDUserInfoViewController.m
//  JYHospital
//
//  Created by 胡金东 on 16/6/14.
//  Copyright © 2016年 胡金东. All rights reserved.
//

#import "HJDUserInfoViewController.h"
#import "HJDNameViewController.h"
#import "AFNetworking.h"
#import "HJDTimeWeekViewController.h"
#import "HJDNickNameViewController.h"
#import "HJDintegralViewController.h"


@interface HJDUserInfoViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic,strong) UIImageView *imageView;
//昵称
@property (nonatomic,strong)  UILabel *nickNameLbl ;
//名字
@property (nonatomic,strong) UILabel *nameLbl;
//预产期
@property (nonatomic,strong) UILabel *timeLbl ;




@end

@implementation HJDUserInfoViewController

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    self.nickNameLbl.text = [[NSUserDefaults standardUserDefaults] stringForKey:@"changNick"];
    
    NSData *nameDa = [[NSUserDefaults standardUserDefaults]valueForKey:@"nameD"];
    NSString *name = [NSKeyedUnarchiver unarchiveObjectWithData:nameDa];

    if (![name isKindOfClass:[NSNull class]]) {
        self.nameLbl.text	= name;
    }
    NSData *dueData = [[NSUserDefaults standardUserDefaults]valueForKey:@"due"];
   NSString *due = [NSKeyedUnarchiver unarchiveObjectWithData:dueData];
    if (![due isKindOfClass:[NSNull class]]) {
        self.timeLbl.text = due;
    }
}



- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor getColorWithHexNumber:@"F1F1EE"];
    self.title = @"个人信息";
    [self.navigationController.navigationBar setTitleTextAttributes:
     @{NSFontAttributeName:[UIFont systemFontOfSize:19],
       NSForegroundColorAttributeName:[UIColor getColorWithHexNumber:@"848484"]}];
    self.navigationItem.leftBarButtonItem = [UIBarButtonItem itemWithTarget:self action:@selector(popToPre) image:@"︿" HighImage:nil];
    
        [self setUpcontent];
  }


//返回
-(void)popToPre
{
    [self dismissViewControllerAnimated:YES completion:nil];
}



-(void)setUpcontent{
    
    CGFloat iconX = 0;
    CGFloat iconY = HJDNavigHeight + HJDVerticalMargin/2;
    CGFloat iconW = HJDWidth;
    CGFloat iconH = 70;
    UIButton *iconBtn = [[UIButton alloc]initWithFrame:CGRectMake(iconX, iconY, iconW, iconH)];
    [iconBtn setTitle:@"头像" forState:UIControlStateNormal];
    [iconBtn setTitleColor:[UIColor getColorWithHexNumber:@"333333"] forState:UIControlStateNormal];
    [iconBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, HJDWidth-50)];
    [iconBtn addTarget:self action:@selector(iconBtnClick) forControlEvents:UIControlEventTouchUpInside];
    iconBtn.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:iconBtn];
    
    self.imageView = [[UIImageView alloc]initWithFrame:CGRectMake(HJDWidth - 50 -30, 10, 99/2, 99/2)];
    [self.imageView setRadius:self.imageView.height/2 borderWith:0 borderColor:nil];
    
    //    加载首先访问本地沙盒是否存在相关图片
        NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:@"currentImage.png"];
        UIImage *savedImage = [UIImage imageWithContentsOfFile:fullPath];
    
        if (!savedImage)
        {
            //默认头像
            self.imageView.image = [UIImage imageNamed:@"新头像"];
        }
        else
        {
            self.imageView.image = savedImage;
        }

    
    [iconBtn addSubview:self.imageView];
    CGFloat iconImageX = CGRectGetMaxX(self.imageView.frame) + 3;
    UIImageView *iconimage = [[UIImageView alloc]initWithFrame:CGRectMake(iconImageX, 99/4, 9, 35/2)];
    iconimage.image = [UIImage imageNamed:@"间号"];
    [iconBtn addSubview:iconimage];
    
    
    CGFloat nickNameX = 0;
    CGFloat nickNameY = CGRectGetMaxY(iconBtn.frame)+1;
    CGFloat nickNameW = HJDWidth;
    CGFloat nickNameH = 50;
    UIButton *nickNameBtn = [[UIButton alloc]initWithFrame:CGRectMake(nickNameX, nickNameY, nickNameW, nickNameH)];
    [nickNameBtn setTitle:@"昵称" forState:UIControlStateNormal];
    [nickNameBtn setTitleColor:[UIColor getColorWithHexNumber:@"333333"] forState:UIControlStateNormal];
    [nickNameBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, HJDWidth-50)];
    [nickNameBtn addTarget:self action:@selector(nickNameBtnClick) forControlEvents:UIControlEventTouchUpInside];
    nickNameBtn.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:nickNameBtn];

    
    self.nickNameLbl = [[UILabel alloc]init];
    self.nickNameLbl.font = [UIFont fontWithName:@"HelveticaNeue" size:19];
    
    NSUserDefaults *de = [NSUserDefaults standardUserDefaults];
    NSString *changeN = [de objectForKey:@"changNick"];
    self.nickNameLbl.text = changeN;
    
    CGSize  nickNameLblSize = [self.nickNameLbl.text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:self.nickNameLbl.font,NSFontAttributeName ,nil]];
    self.nickNameLbl.textAlignment = NSTextAlignmentCenter;
    CGFloat nickNameLblX = HJDWidth - 40 - nickNameLblSize.width;
    CGFloat nickNameLblY = 10;
    self.nickNameLbl.frame = (CGRect){{nickNameLblX,nickNameLblY +5},nickNameLblSize};
    self.nickNameLbl.textColor = [UIColor getColorWithHexNumber:@"333333"];
    [nickNameBtn addSubview:self.nickNameLbl];
    
    
    UIImageView *nickNameimage = [[UIImageView alloc]initWithFrame:CGRectMake(iconImageX, (50-35/2)/2+2, 9, 35/2)];
    nickNameimage.image = [UIImage imageNamed:@"间号"];
    [nickNameBtn addSubview:nickNameimage];
    
    CGFloat nameX = 0;
    CGFloat nameY = CGRectGetMaxY(nickNameBtn.frame)+1;
    CGFloat nameW = HJDWidth;
    CGFloat nameH = 50;
    UIButton *nameBtn = [[UIButton alloc]initWithFrame:CGRectMake(nameX, nameY, nameW, nameH)];
    [nameBtn setTitle:@"名字" forState:UIControlStateNormal];
    [nameBtn setTitleColor:[UIColor getColorWithHexNumber:@"333333"] forState:UIControlStateNormal];
    [nameBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, HJDWidth-50)];
    [nameBtn addTarget:self action:@selector(nameBtnClick) forControlEvents:UIControlEventTouchUpInside];
    nameBtn.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:nameBtn];
    
    NSData *nameDa = [[NSUserDefaults standardUserDefaults]valueForKey:@"nameD"];
    NSString *name = [NSKeyedUnarchiver unarchiveObjectWithData:nameDa];
    

    self.nameLbl = [[UILabel alloc]init];
//    刚开始传进来时候为NSNull，我们要判断一下
        if (![name isKindOfClass:[NSNull class]]) {
            self.nameLbl.text	= name;
        }
    self.nameLbl.font = [UIFont fontWithName:@"HelveticaNeue" size:19];
    
    CGSize  nameLblSize = [self.nameLbl.text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:self.nameLbl.font,NSFontAttributeName ,nil]];
    self.nameLbl.textAlignment = NSTextAlignmentCenter;
    CGFloat nameLblX = HJDWidth - 30 - nameLblSize.width;
    CGFloat nameLblY = 10;
    self.nameLbl.frame = (CGRect){{nameLblX,nameLblY +5},nameLblSize};
    self.nameLbl.textColor = [UIColor getColorWithHexNumber:@"333333"];
    [nameBtn addSubview:self.nameLbl];

    
    UIImageView *nameimage = [[UIImageView alloc]initWithFrame:CGRectMake(iconImageX, (50-35/2)/2+2, 9, 35/2)];
    nameimage.image = [UIImage imageNamed:@"间号"];
    [nameBtn addSubview:nameimage];
    
    CGFloat timeX = 0;
    CGFloat timeY = CGRectGetMaxY(nameBtn.frame)+1;
    CGFloat timeW = HJDWidth;
    CGFloat timeH = 50;
    UIButton *timeBtn = [[UIButton alloc]initWithFrame:CGRectMake(timeX, timeY, timeW, timeH)];
    [timeBtn setTitle:@"预产期" forState:UIControlStateNormal];
    [timeBtn setTitleColor:[UIColor getColorWithHexNumber:@"333333"] forState:UIControlStateNormal];
    [timeBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, HJDWidth-70)];
    [timeBtn addTarget:self action:@selector(timeBtnClick) forControlEvents:UIControlEventTouchUpInside];
    timeBtn.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:timeBtn];
    
    self.timeLbl = [[UILabel alloc]init];
    NSUserDefaults *defaD = [NSUserDefaults standardUserDefaults];
    NSString *preD = [defaD objectForKey:@"pregnanc"];
    
    NSDateFormatter *inputFormatter = [[NSDateFormatter alloc] init];
    [inputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    [inputFormatter setDateFormat:@"yyyy-MM-dd"];
    NSDate *inputDate = [inputFormatter dateFromString:preD];
    NSDate *nextDate = [NSDate dateWithTimeInterval:24*60*60 * 280 sinceDate:inputDate];

    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *strDate = [dateFormatter stringFromDate:nextDate];
    
    self.timeLbl.text = strDate;
    self.timeLbl.font = [UIFont fontWithName:@"HelveticaNeue" size:19];
    
    CGSize  timeLblSize = [self.timeLbl.text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:self.timeLbl.font,NSFontAttributeName ,nil]];
    self.timeLbl.textAlignment = NSTextAlignmentCenter;
    CGFloat timeLblX = HJDWidth - 30 - timeLblSize.width;
    CGFloat timeLblY = 10;
    self.timeLbl.frame = (CGRect){{timeLblX,timeLblY +5},timeLblSize};
    self.timeLbl.textColor = [UIColor getColorWithHexNumber:@"333333"];
    [timeBtn addSubview:self.timeLbl];
    
    
    UIImageView *timeimage = [[UIImageView alloc]initWithFrame:CGRectMake(iconImageX, (50-35/2)/2+2, 9, 35/2)];
    timeimage.image = [UIImage imageNamed:@"间号"];
    [timeBtn addSubview:timeimage];
    
    
    CGFloat phoneX = 0;
    CGFloat phoneY = CGRectGetMaxY(timeBtn.frame) + HJDVerticalMargin/2;
    CGFloat phoneW = HJDWidth;
    CGFloat phoneH = 50;
    UIButton *phoneBtn = [[UIButton alloc]initWithFrame:CGRectMake(phoneX, phoneY, phoneW, phoneH)];
    [phoneBtn setTitle:@"绑定手机号" forState:UIControlStateNormal];
    [phoneBtn setTitleColor:[UIColor getColorWithHexNumber:@"333333"] forState:UIControlStateNormal];
    [phoneBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, HJDWidth-100)];
    [phoneBtn addTarget:self action:@selector(phoneBtnClick) forControlEvents:UIControlEventTouchUpInside];
    phoneBtn.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:phoneBtn];
    
    
    UILabel *phoneLbl = [[UILabel alloc]init];
    NSString *phone = @"15703973333";
    NSString *tel = [phone stringByReplacingCharactersInRange:NSMakeRange(7, 4) withString:@"****"];
    phoneLbl.text = tel ;
    phoneLbl.font = [UIFont fontWithName:@"HelveticaNeue" size:19];
    
    CGSize  phoneLblSize = [phoneLbl.text sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:phoneLbl.font,NSFontAttributeName ,nil]];
    phoneLbl.textAlignment = NSTextAlignmentCenter;
    CGFloat phoneLblX = HJDWidth - 30 - phoneLblSize.width;
    CGFloat phoneLblY = 10;
    phoneLbl.frame = (CGRect){{phoneLblX,phoneLblY +5},phoneLblSize};
    phoneLbl.textColor = [UIColor getColorWithHexNumber:@"333333"];
    [phoneBtn addSubview:phoneLbl];
    
    UIImageView *phoneimage = [[UIImageView alloc]initWithFrame:CGRectMake(iconImageX, (50-35/2)/2, 9, 35/2)];
    phoneimage.image = [UIImage imageNamed:@"间号"];
    [phoneBtn addSubview:phoneimage];
    
    
//    积分
    CGFloat integralX = 0;
    CGFloat integralY = CGRectGetMaxY(phoneBtn.frame) + HJDVerticalMargin/2;
    CGFloat integralW = HJDWidth;
    CGFloat integralH = 50;
    UIButton *integralBtn = [[UIButton alloc]initWithFrame:CGRectMake(integralX, integralY, integralW, integralH)];
    [integralBtn setTitle:@"我的积分" forState:UIControlStateNormal];
    [integralBtn setTitleColor:[UIColor getColorWithHexNumber:@"333333"] forState:UIControlStateNormal];
    [integralBtn setTitleEdgeInsets:UIEdgeInsetsMake(0, 10, 0, HJDWidth-85)];
    [integralBtn addTarget:self action:@selector(integralBtnClick) forControlEvents:UIControlEventTouchUpInside];
    integralBtn.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:integralBtn];
    
    
    UIImageView *integralimage = [[UIImageView alloc]initWithFrame:CGRectMake(iconImageX, (50-35/2)/2, 9, 35/2)];
    integralimage.image = [UIImage imageNamed:@"间号"];
    [integralBtn addSubview:integralimage];

    
    
}

-(void)iconBtnClick
{
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"获取照片" message:@"" preferredStyle:UIAlertControllerStyleActionSheet];
    //    判断是否支持相机
        if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
            UIAlertAction *action = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    //            相机
                UIImagePickerController *imageP = [[UIImagePickerController alloc]init];
                imageP.delegate = self;
                imageP.allowsEditing = YES;
                imageP.sourceType = UIImagePickerControllerSourceTypeCamera;
                [self presentViewController:imageP animated:YES completion:nil];
            }];
            [alert addAction:action];
        }
        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            UIImagePickerController *imageP = [[UIImagePickerController alloc]init];
            imageP.delegate = self;
            imageP.allowsEditing = YES;
            imageP.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    
            [self presentViewController:imageP animated:YES completion:nil];
    
        }];
        UIAlertAction *cancel = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    
        }];
        [alert addAction:cancel];
    
        [alert addAction:alertAction];
        [self presentViewController:alert animated:YES completion:nil];
}



#pragma mark - 选择图片后,回调选择

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    
//        保存图片至本地，上传图片到服务器需要使用
//        [self saveImage:img Name:@"avatar.png"];
//        NSString *fullpath = [[NSHomeDirectory()stringByAppendingPathComponent:@"Documents"]stringByAppendingPathComponent:@"avatar.png"];
//        UIImage *saveImage = [[UIImage alloc]initWithContentsOfFile:fullpath];


//    [self saveImage: img Name:@"currentImage.png"];
//    [picker dismissViewControllerAnimated:YES completion:nil];
    UIImage *img = [info objectForKey:UIImagePickerControllerEditedImage];
    


    NSString *url = @"/app/modifyImage.do";
    NSString *path = [Hurl stringByAppendingString:url];
    AFHTTPSessionManager *mgr = [AFHTTPSessionManager manager];
    NSMutableDictionary *params = [NSMutableDictionary dictionary];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSString *phone = [defaults objectForKey:@"phonenum"];
    params[@"phone"]= phone;
   [mgr POST:path parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
       NSData *imageData = UIImageJPEGRepresentation(img , 1.0f);
       [formData appendPartWithFileData:imageData name:@"upload" fileName:@"upload.jpg" mimeType:@"image/jpg"];
   } progress:^(NSProgress * _Nonnull uploadProgress) {
       
   } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
      
       NSDictionary *Info =(NSDictionary *)responseObject;
       NSString *infoUrl = Info[@"resultMap"][@"imageUrl"];
       
       NSString *urlstring = [NSString stringWithFormat:@"%@/%@",headImageUrl,infoUrl];
       self.imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:urlstring]]];
       [self saveImage:self.imageView.image Name:@"currentImage.png"];
       
   } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
       [MBProgressHUD showError:@"服务器升级，请稍后再试"];
   }];
   
    [picker dismissViewControllerAnimated:YES completion:nil];

    

  }

#pragma mark - 保存图片至本地沙盒
-(void)saveImage:(UIImage *)currentImage Name:(NSString *)imageName{
    
    NSData * imageData = UIImageJPEGRepresentation(currentImage, 1);//1为不缩放保存，取值（0.0-1.0）
    //    获取沙盒目录
    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imageName];
    //    将图片写入文件
    [imageData writeToFile:fullPath atomically:NO];
    
}



-(void)nameBtnClick{
    HJDNameViewController *name = [[HJDNameViewController alloc]init];

    [self.navigationController pushViewController:name animated:YES];
}

-(void)nickNameBtnClick{
    HJDNickNameViewController *nickName = [[HJDNickNameViewController alloc]init];
    [self.navigationController pushViewController:nickName animated:YES];
}




-(void)timeBtnClick{
    
    HJDTimeWeekViewController *timeWeek = [[HJDTimeWeekViewController alloc]init];
    [self.navigationController pushViewController:timeWeek animated:YES];
    }

-(void)phoneBtnClick{
//    HJDLog(@"点击手机号");
}
//积分
-(void)integralBtnClick
{
    HJDintegralViewController *inter = [[HJDintegralViewController alloc]init];
    [self.navigationController pushViewController:inter animated:YES];
    
}



@end
